<template>
  <div>
    <view v-for="(v, i) in dataSource" :key="i">
      <BasicTable
        :columns="getColumns(v.type)"
        :dataSource="[v]"
        bordered
        :pagination="false"
        :canResize="false"
        :showIndexColumn="false"
        :ref="(el) => getRef(el, i)"
        :rowSelection="{ type: 'checkbox' }"
        :customRow="customRow"
        :scroll="{ x: true }"
      >
        <template #tenderResponseUrlApplyPay="{ record }">
          <div
            v-if="record.tenderApplyResponse?.voucher"
            class="file_download"
            @click="fileDownloadFn(record, 'tenderResponseUrlApplyPay')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #contractApplyResponseUrl="{ record }">
          <div
            v-if="record.contractApplyResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'contractApplyResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #designApplyResponseUrl="{ record }">
          <div
            v-if="record.designApplyResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'designApplyResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #checkApplyResponseUrl="{ record }">
          <div
            v-if="record.checkApplyResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'checkApplyResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #invoiceApplyResponseUrl="{ record }">
          <div
            v-if="record.invoiceApplyResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'invoiceApplyResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #tenderApplyResponseUrl="{ record }">
          <div
            v-if="record.tenderApplyResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'tenderApplyResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>

        <template #contractApplyResponseAction="{ record }">
          <div class="action" v-if="record.contractApplyResponse.stage == '1'">
            <Popconfirm
              :title="`您确定同意吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="editConfirm(record.contractApplyResponse, 'hetong', '2')"
            >
              <div class="del_class">同意</div>
            </Popconfirm>
            <Popconfirm
              :title="`您确定拒绝吗？`"
              @confirm="editConfirm(record.contractApplyResponse, 'hetong', '3')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">拒绝</div>
            </Popconfirm>
          </div>
        </template>
        <template #designApplyResponseAction="{ record }">
          <div class="action" v-if="record.designApplyResponse.stage == '1'">
            <Popconfirm
              :title="`您确定同意吗？`"
              @confirm="editConfirm(record.designApplyResponse, 'chutu', '2')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">同意</div>
            </Popconfirm>
            <Popconfirm
              :title="`您确定拒绝吗？`"
              @confirm="editConfirm(record.designApplyResponse, 'chutu', '3')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">拒绝</div>
            </Popconfirm>
          </div>
        </template>
        <template #checkApplyResponseAction="{ record }">
          <div class="action" v-if="record.checkApplyResponse.stage == '1'">
            <Popconfirm
              :title="`您确定同意吗？`"
              @confirm="editConfirm(record.checkApplyResponse, 'yanshou', '2')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">同意</div>
            </Popconfirm>
            <Popconfirm
              :title="`您确定拒绝吗？`"
              @confirm="editConfirm(record.checkApplyResponse, 'yanshou', '3')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">拒绝</div>
            </Popconfirm>
          </div>
        </template>
        <template #invoiceApplyResponseAction="{ record }">
          <div class="action" v-if="record.invoiceApplyResponse.stage == '1'">
            <Popconfirm
              :title="`您确定同意吗？`"
              @confirm="editConfirm(record.invoiceApplyResponse, 'fapiao', '2')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">同意</div>
            </Popconfirm>
            <Popconfirm
              :title="`您确定拒绝吗？`"
              @confirm="editConfirm(record.invoiceApplyResponse, 'fapiao', '3')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">拒绝</div>
            </Popconfirm>
          </div>
        </template>
        <template #tenderApplyResponseAction="{ record }">
          <div class="action" v-if="record.tenderApplyResponse.stage == '1'">
            <Popconfirm
              :title="`您确定同意吗？`"
              @confirm="editConfirm(record.tenderApplyResponse, 'zhao', '2')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">同意</div>
            </Popconfirm>
            <Popconfirm
              :title="`您确定拒绝吗？`"
              @confirm="editConfirm(record.tenderApplyResponse, 'zhao', '3')"
              ok-text="确定"
              cancel-text="取消"
            >
              <div class="del_class">拒绝</div>
            </Popconfirm>
          </div>
        </template>
      </BasicTable>
    </view>
  </div>
</template>
<script lang="ts" setup>
  import { message, Table, Popconfirm } from 'ant-design-vue';
  import { ref, onMounted } from 'vue';
  import {
    logQueryApi,
    fileDownloadApi,
    applyLogAllQueryApi,
    modifyFapiaoAuditState,
    modifyChutuAuditState,
    modifyZhaoTouBiaoAuditState,
    modifyHetongAuditState,
    modifyYanshouAuditState,
  } from '/@/api/projectManagement';
  import { useRouter, useRoute } from 'vue-router';
  import { columns1, columns2, columns3, columns4, columns5 } from './datas.ts';

  import { queryAllLicense } from '/@/api/api';
  import { BasicTable } from '/@/components/Table';
  import * as XLSX from 'xlsx/xlsx.mjs';
  // import XLSX from 'xlsx-style';
  import { Item } from 'ant-design-vue/lib/menu';

  const recordsArr = ref([
    {
      name: '合同记录',
      kind: 'hetong',
    },
    {
      name: '出图记录',
      kind: 'chutu',
    },
    {
      name: '发票记录',
      kind: 'fapiao',
    },
    {
      name: '招投标记录',
      kind: 'zhao',
    },
    {
      name: '验收记录',
      kind: 'yan',
    },
  ]);

  const allLicense = ref([]);

  const route = useRoute();
  onMounted(() => {
    getTableData();
    console.log(route.query.id);
    queryAllLicense().then((res) => {
      allLicense.value = res;
    });
  });

  const dataSource = ref([]); //table数据
  const getTableData = () => {
    applyLogAllQueryApi({
      projectId: route.query.id,
    }).then((res) => {
      dataSource.value = res || [];
    });
    // dataSource.value = [
    //   { name: 'asd', color: '#00ff00' },
    //   { name: 'asd', color: '#ff0000' },
    //   { name: 'asd', color: '#0000ff' },
    // ];
  };
  // 根据类型获取对应表格配置
  const getChildName = (type) => {
    let obj = {
      10: 'contractApplyResponse',
      11: 'designApplyResponse',
      12: 'checkApplyResponse',
      13: 'invoiceApplyResponse',
      14: 'tenderApplyResponse',
    };
    return obj[type] || {};
  };

  const getRowColor = (record) => {
    let type = getChildName(record.type);
    let id = record[type].licenseCompanyId;
    if (!id) return '#fff';
    const license = allLicense.value.find((license) => license.id == id);
    return license ? license.color : '#fff';
  };

  const customRow = (record) => {
    return {
      // style: {
      //   background: getRowColor(record),
      // },
      class: 'asdant',
      onClick: () => {
        console.log('点击了');
      },
    };
  };

  // 合同附件下载
  const fileDownloadFn = (record, key) => {
    let obj = {
      contractApplyResponse: '合同记录',
      designApplyResponse: '出图记录',
      checkApplyResponse: '验收记录',
      invoiceApplyResponse: '发票记录',
      tenderApplyResponse: '招投标记录',
      tenderResponseUrlApplyPay: '支付凭证附件',
    };
    fileDownloadApi(`${record[key].url}`).then((res) => {
      if (key == 'tenderResponseUrlApplyPay') {
        download(res, `${record.projectName}${obj[key]}附件.${record[key].voucher.split('.')[1]}`);
      } else {
        download(res, `${record.projectName}${obj[key]}附件.${record[key].url.split('.')[1]}`);
      }
    });
  };
  // blob下载
  const download = (blob, name) => {
    const link = document.createElement('a'); //创建一个a标签
    const url = window.URL.createObjectURL(blob); //将blob文件对象通过URL.createObjectURL()方法转为为url
    link.href = url; //为a标签设置href属性，并赋值为url
    link.download = name; //定义下载的文件名，文件名要包含后缀哟！如'导出EXCEL.xlsx'
    document.body.appendChild(link); //把a标签放在body上
    link.click(); //出发a标签点击下载
    document.body.removeChild(link); //在body中移除这个a标签
    URL.revokeObjectURL(url); //释放blob对象
  };

  // 根据类型获取对应表格配置
  const getColumns = (type) => {
    let obj = { 10: columns1, 11: columns2, 12: columns3, 13: columns4, 14: columns5 };
    return obj[type] || {};
  };

  const selectedRowKeys: any = ref([]);
  const onSelectChange = (rowKeys, i) => {
    console.log('selectedRowKeys rowKeys: ', rowKeys);
    console.log('selectedRowKeys b: ', selectedRowKeys.value);
    console.log('refList ', refList.value);
    selectedRowKeys.value[i] = rowKeys;
  };

  //储存每一个ref
  const refList: any = ref([]);
  const getRef = (el, index) => {
    if (el) {
      refList.value[index] = el;
    }
  };

  /**
   *
   * @param record 行数据
   * @param kind 记录类型
   * @param stage 1 申请  2 通过  3 拒绝
   */
  const editConfirm = (record, kind, stage) => {
    let data = {
      id: record.id,
      stage: stage,
    };
    let str = stage == '2' ? '已通过' : '已拒绝';
    if (kind == 'hetong') {
      modifyHetongAuditState(data).then(async () => {
        await getTableData();
        message.success(str);
      });
    } else if (kind == 'chutu') {
      modifyChutuAuditState(data).then(async () => {
        await getTableData();
        message.success(str);
      });
    } else if (kind == 'fapiao') {
      modifyFapiaoAuditState(data).then(async () => {
        getTableData();
        message.success(str);
      });
    } else if (kind == 'zhao') {
      modifyZhaoTouBiaoAuditState(data).then(async () => {
        await getTableData();
        message.success(str);
      });
    } else if (kind == 'yanshou') {
      modifyYanshouAuditState(data).then(async () => {
        await getTableData();
        message.success(str);
      });
    }
  };
</script>
<style lang="less" scoped>
  .add_project {
    margin: 10px;
    button {
      margin-right: 10px;
    }
  }
  .action {
    > div,
    .del_class {
      color: #1990ff;
      cursor: pointer;
      margin: 5px 0;
    }
  }
  .file_download {
    cursor: pointer;
    color: rgba(0, 175, 233);
  }
</style>
